<?php
/*
Plugin Name: x7Host's Videox7 UGC Plugin
Plugin URI: http://www.kalturacehost.com
Description: Leverage the power of open source video to start your own user generated content video website.
Version: 0.8 Beta
Author: x7Host
Author URI: http://www.x7host.com
License: GPL2

Copyright 2010 ExSeven, LLC (email : x7host@x7host.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as 
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

//enqueue styles and scripts
add_action('after_setup_theme', 'enqueue_my_styles');
function enqueue_my_styles(){
	//jquery ui style
	wp_enqueue_style('jqueryui-style', plugins_url( 'css/smoothness/jquery-ui-1.8.4.custom.css', __FILE__ ));
	//shadowbox (lightbox) style
	wp_enqueue_style('shadowbox-style', plugins_url( 'css/sbox/shadowbox.css', __FILE__ ));
	//x7video custom style
	wp_enqueue_style('x7video-style', plugins_url( 'css/x7style.css', __FILE__ ));
	//datatables
	wp_enqueue_style('datatables-style', plugins_url( 'css/datatables/css/demo_table_jui.css', __FILE__ ));
}
//prints necessary javascripts only when needed and in the footer
add_action('wp_footer', 'print_my_scripts');
function print_my_scripts() {
	global $add_my_script;
 
	if ( ! $add_my_script )
		return;
    //register swfobject for flash embedding
    wp_register_script('swfobject-script', 'http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js', false, false, true);
    //unregister WP's jquery and register newest jquery
    wp_deregister_script('jquery');
    //includes jquery tools ui
    wp_register_script('jquery', 'http://cdn.jquerytools.org/1.2.4/jquery.tools.min.js', false, false, true);
    //register newest jquery ui
	wp_register_script('jqueryui-script', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js', false, false, true);
	//register shadowbox
	wp_register_script('shadowbox-script', plugins_url( 'js/shadowbox.js', __FILE__), false, false, true);
    //register custom x7js
	wp_register_script('x7ugc-script', plugins_url( 'js/x7js.js', __FILE__), false, false, true);
	//register form validator
	wp_register_script('x7validator-script', plugins_url( 'js/validator.js', __FILE__), false, false, true);
	//register datatables
	wp_register_script('x7datatables-script', plugins_url( 'js/jquery.dataTables.min.js', __FILE__), false, false, true);
    //print all scripts
	wp_print_scripts('swfobject-script');
	wp_print_scripts('jquery');
	wp_print_scripts('jqueryui-script');
	wp_print_scripts('shadowbox-script');
	wp_print_scripts('x7ugc-script');
	wp_print_scripts('x7validator-script');
	wp_print_scripts('x7datatables-script');
}

// create custom plugin settings menu
add_action('admin_menu', 'x7_create_menu');

/* COMING SOON
//add video comment hook
add_action('comment_form', 'add_video_comment');
*/

function x7_create_menu() {

	//create new top-level menu
	add_menu_page('x7Host Videox7 UGC Plugin Settings', 'x7 UGC Settings', 'administrator', __FILE__, 'x7_settings_page',plugins_url('/images/icon.png', __FILE__));

	//call register settings function
	add_action( 'admin_init', 'register_mysettings' );
}

function register_mysettings() {
	//register our settings
	register_setting( 'x7-settings-group', 'x7server' );
	register_setting( 'x7-settings-group', 'x7kshowid' );
	register_setting( 'x7-settings-group', 'x7tou' );
	register_setting( 'x7-settings-group', 'x7uiconfid' );
	register_setting( 'x7-settings-group', 'x7pluiconfid' );
	register_setting( 'x7-settings-group', 'x7adminuiconfid' );
	register_setting( 'x7-settings-group', 'x7kcwuiconfid' );
	register_setting( 'x7-settings-group', 'x7kalusersecret' );
	register_setting( 'x7-settings-group', 'x7kaladminsecret' );
	register_setting( 'x7-settings-group', 'x7kalpartnerid' );
	register_setting( 'x7-settings-group', 'x7allowposts' );
	register_setting( 'x7-settings-group', 'x7jcsitename' );
	register_setting( 'x7-settings-group', 'x7jcapikey' );
	register_setting( 'x7-settings-group', 'x7jcsecret' );
	register_setting( 'x7-settings-group', 'x7allowimports' );
}

//PHP REST helper function that does not use CURL
function rest_helper($url, $params = null, $verb = 'POST', $format = 'xml')
{
  $cparams = array(
    'http' => array(
      'method' => $verb,
      'ignore_errors' => true
    )
  );
  if ($params !== null) {
    $params = http_build_query($params);
    if ($verb == 'POST') {
      $cparams['http']['content'] = $params;
    } else {
      $url .= '?' . $params;
    }
  }

  $context = stream_context_create($cparams);
  $fp = fopen($url, 'rb', false, $context);
  if (!$fp) {
    $res = false;
  } else {
    // If you're trying to troubleshoot problems, try uncommenting the
    // next two lines; it will show you the HTTP response headers across
    // all the redirects:
    // $meta = stream_get_meta_data($fp);
    // var_dump($meta['wrapper_data']);
    $res = stream_get_contents($fp);
  }

  if ($res === false) {
    throw new Exception("$verb $url failed: $php_errormsg");
  }

  switch ($format) {
    case 'json':
      $r = json_decode($res);
      if ($r === null) {
        throw new Exception("failed to decode $res as json");
      }
      return $r;

    case 'xml':
      $r = simplexml_load_string($res);
      if ($r === null) {
        throw new Exception("failed to decode $res as xml");
      }
      return $r;
  }
  return $res;
}
/* THIS IS COMING SOON!
//ADD POST VIDEO COMMENT ACTION HOOK
function add_video_comment()
{
	$return2 .= <<<VIDCOMMENT
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://cdn.jquerytools.org/1.2.4/jquery.tools.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/shadowbox.js?ver=3.0.1'></script>
VIDCOMMENT;
	$return2 .= "<br><br>TEST.";
	echo "$return2";
}
*/

//SHORTCODES!!!
// [x7video widget="kcw" bar="whatev"] currently only "widget" attribute is supported
function x7video_func($atts) {
	extract(shortcode_atts(array(
		//Kaltura uploader is default widget
		'widget' => 'kcw',
		'bar' => 'whatever',
	), $atts));
	//First, master check for logged in wordpress user.  ALL widgets will not function if this fails.
if (is_user_logged_in()){
	//Set add scripts global to true, which results in javascripts printing in footer
	global $add_my_script;
	$add_my_script = true;
	//Get wordpress user info, both login nicename (used by Kaltura) and ID (used by JayCut)
		global $user_login;
		global $user_ID;
		get_currentuserinfo();
	//GET KALTURA SETTINGS
		$x7server = get_option(x7server);
		$x7serverget = urlencode($x7server);
		$x7uiconfid = get_option(x7uiconfid);
		$x7pluiconfid = get_option(x7pluiconfid);
		$x7kshowid = get_option(x7kshowid);
		$x7kcwuiconfid = get_option(x7kcwuiconfid);
		$x7kalusersecret = get_option(x7kalusersecret);
		$x7kaladminsecret = get_option(x7kaladminsecret);
		$x7kalpartnerid = get_option(x7kalpartnerid);
		$x7kalsubpartnerid = "$x7kalpartnerid * 100";
		$x7tou = get_option(x7tou);
		$x7allowposts = get_option(x7allowposts);
		$x7adminuiconfid = get_option(x7adminuiconfid);
	//GET JAYCUT SETTINGS
		$x7jcsitename = get_option(x7jcsitename);
		$x7jcapikey = get_option(x7jcapikey);
		$x7jcsecret = get_option(x7jcsecret);
		$x7allowimports = get_option(x7allowimports);
	//GET ENV SETTINGS
		$x7bloghome = get_bloginfo('url');
		$x7bloghomeget = urlencode($x7bloghome);
		$pluginurl = plugins_url();
		
	if ($widget=="kcw"){
		//Kaltura Contribution Wizard (Uploader)
		//Start Kaltura "User" Session
		include_once("KalturaClient.php");
		define("KALTURA_PARTNER_ID", "$x7kalpartnerid");
		define("KALTURA_PARTNER_SERVICE_SECRET", "$x7kalusersecret");
		$config           = new KalturaConfiguration();
		$config->serviceUrl = $x7server;
		$client           = new KalturaClient($config);
		$type = KalturaSessionType::USER;
		$expiry = null;
		$privileges = null;
		$ks = $client->session->start(KALTURA_PARTNER_SERVICE_SECRET, "$user_login", $type, KALTURA_PARTNER_ID, $expiry, $privileges);
		//Embed the KCW
		$return .= '<div id="kcw"></div>';
		$return .= "<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'></script>";
		$return .= <<<X7KCW
		
		<script type="text/javascript">
		var params = {
			allowScriptAccess: "always",
			allowNetworking: "all",
			wmode: "opaque"
		};
		var flashVars = {"Permissions":"1","partnerId":"$x7kalpartnerid","uid":"$user_login","ks":"$ks","kshowId":"$x7kshowid","terms_of_use":"$x7tou","afterAddEntry":"onContributionWizardAfterAddEntry","close":"onContributionWizardClose","showCloseButton":"false"};
		swfobject.embedSWF("$x7server/kcw/ui_conf_id/$x7kcwuiconfid", "kcw", "680", "360", "9.0.0", false, flashVars, params);
		function onContributionWizardAfterAddEntry(entries) {
			alert(entries.length + " media file/s was/were succsesfully uploaded. Please allow time for conversion. Page will refresh now.");
			//for(var i = 0; i < entries.length; i++) {
			//		alert("entries["+i+"]:EntryID = " + entries[i].entryId);
			//}
		}
		function onContributionWizardClose() {
				window.location.reload();
		}
		</script>
X7KCW;
	} //end if widget is kcw
	
	if ($widget=="useruploads"){
		//This widget displays the logged in user's Kaltura uploads and offers the ability to
		//play, edit (remix), delete and post them as drafts to the wordpress blog
		//Start Kaltura "Admin" Session
		include_once("KalturaClient.php");
		define("KALTURA_PARTNER_ID", "$x7kalpartnerid");
		define("KALTURA_PARTNER_SERVICE_SECRET", "$x7kaladminsecret");
		$config           = new KalturaConfiguration();
		$config->serviceUrl = $x7server;
		$client           = new KalturaClient($config);
		$type = KalturaSessionType::ADMIN;
		$ks = $client->session->start(KALTURA_PARTNER_SERVICE_SECRET, "$user_login", $type, KALTURA_PARTNER_ID, $expiry, $privileges);
		$ksget = urlencode($ks);
		
		//SET RPCURL XMLRPC FILE VALUE
		$x7rpcurl = $x7bloghome . "/xmlrpc.php";
		$x7fullplugurl = plugins_url('/ixr.php', __FILE__);
		$playurl = plugins_url('x7vidplayer.php', __FILE__);
                        $pluginurl = plugins_url();
                        $pluginurlget = urlencode($pluginurl);
                        $advancedediturl = plugins_url('x7advancededitor.php', __FILE__);
			$standardediturl = plugins_url('x7standardeditor.php', __FILE__);
		//GET CATEGORIES LIST
		$categories = get_categories('hide_empty=0'); 
			foreach ($categories as $cat) {
				$option .= "<option value=\"$cat->cat_name\">$cat->cat_name</option>";
			}
		
		//EMBED DELETE JAVASCRIPT FUNCTION AND POST FUNCTION AND GET VARIABLE READER
		$return.= <<<DELETE_JS
		
		<style type="text/css">
		#x7form { width: 400px; }
		.tooltip {
				display:none;
				background:transparent url($pluginurl/x7video/images/black_arrow.png);
				font-size:12px;
				height:70px;
				width:160px;
				padding:25px;
				color:#fff;	
			}
		</style>
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://cdn.jquerytools.org/1.2.4/jquery.tools.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/shadowbox.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/x7js.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/validator.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/jquery.dataTables.min.js?ver=3.0.1'></script>

		<script type="text/javascript">
		
			function x7VidPlay()
			{
				var eid = jQuery("a#x7aplaychange").attr("title");
				var playurl = '$playurl'+'?eid='+eid+'&x7kalpartnerid=$x7kalpartnerid&x7bloghomeget=$x7bloghomeget&x7server=$x7serverget&x7uiconfid=$x7adminuiconfid';
				Shadowbox.open({
					content: playurl,
					player: "iframe",
					height: "370",
					width: "405"
				});
			}
			
			function x7VidEditStandard()
			{
				var eid = jQuery("a#x7aeditchange").attr("title");
				var name = jQuery("a#x7aeditchange").attr("name");
				jQuery.post(
					"$pluginurl/x7video/x7mixcreate.php",
					{'x7bloghome': '$x7bloghome', 'x7server': "$x7server", 'ks': "$ks", 'x7editortype': '1', 'eid': eid, 'x7name': name, 'x7kalpartnerid': "$x7kalpartnerid", 'user_login': "$user_login"},
					function ( response ){
						jQuery('div#x7form').hide('slow');
						jQuery('div#x7tablewrap').show('slow');
						var editurl = '$standardediturl'+'?entryId='+response+'&ks=$ksget&x7kalpartnerid=$x7kalpartnerid&x7bloghomeget=$x7bloghomeget&x7kalusersecret=$x7kalusersecret&userlogin=$user_login&x7server=$x7serverget&pluginurl=$pluginurlget';
						Shadowbox.open({
						content: editurl,
						player: "iframe",
						height: "600",
						width: "1000"
					});
				});
			}
			
			function x7VidEditAdvanced()
			{
				var eid = jQuery("a#x7aedit2change").attr("title");
				var name = jQuery("a#x7aedit2change").attr("name");
				jQuery.post(
					"$pluginurl/x7video/x7mixcreate.php",
					{'x7bloghome': '$x7bloghome', 'x7server': "$x7server", 'ks': "$ks", 'x7editortype': '2', 'eid': eid, 'x7name': name, 'x7kalpartnerid': "$x7kalpartnerid", 'user_login': "$user_login"},
					function ( response ){
						jQuery('div#x7form').hide('slow');
						jQuery('div#x7tablewrap').show('slow');
						var editurl = '$advancedediturl'+'?entryId='+response+'&ks=$ksget&x7bloghomeget=$x7bloghomeget&x7kalpartnerid=$x7kalpartnerid&x7kalusersecret=$x7kalusersecret&userlogin=$user_login&x7server=$x7serverget&pluginurl=$pluginurlget';
						Shadowbox.open({
						content: editurl,
						player: "iframe",
						height: "600",
						width: "1000"
					});
				});
			}
		
			function x7VidDelete()
			{
				var delid = jQuery("a#x7adelchange").attr("title");
				if (confirm("Warning! This will affect all mixes that include entry ID: " + delid + ". Continue?"))
				{ 
				    jQuery.post(
				       "$pluginurl/x7video/x7delete.php",
				       {'x7bloghome': '$x7bloghome', 'ks': "$ks", 'x7entrytype': 'media', 'eid': delid, 'x7server': "$x7server"},
				       function ( response ){
					      jQuery("#x7entriestable tbody tr [title="+delid+"]").remove();
					      jQuery('div#x7form').hide('slow');
						jQuery('div#x7tablewrap').show('slow');
						alert("Entry successfully deleted.");
					      //var x7nodes = x7Table.fnGetNodes();
					      //TODO NEED TO REMOVE APPROPRIATE ROW FROM THE TABLE AND REFRESH TABLE
				       });//end post
				} //end confirm
			} //end x7VidDelete
			var postout;
			postout = 'false';
			function x7VidPost(eid, name)
			{
				if (postout == 'false'){
					formValidate();
					var thumburl = '$x7server/p/1/sp/$x7kalpartnerid/thumbnail/entry_id/'+eid+'/width/150/height/120';
					var embedcode = '<object id="kaltura_player" name="kaltura_player" type="application/x-shockwave-flash" allowFullScreen="true" allowNetworking="all" allowScriptAccess="always" height="330" width="400" xmlns:dc="http://purl.org/dc/terms/" xmlns:media="http://search.yahoo.com/searchmonkey/media/" rel="media:video" resource="$x7server/index.php/kwidget/cache_st/1283996450/wid/_100/uiconf_id/$x7uiconfid/entry_id/'+eid+'" data="$x7server/index.php/kwidget/cache_st/1283996450/wid/_100/uiconf_id/$x7uiconfid/entry_id/'+eid+'"><param name="allowFullScreen" value="true" /><param name="allowNetworking" value="all" /><param name="allowScriptAccess" value="always" /><param name="bgcolor" value="#000000" /><param name="flashVars" value="&" /><param name="movie" value="$x7server/index.php/kwidget/cache_st/1283996450/wid/_100/uiconf_id/$x7uiconfid/entry_id/'+eid+'" /><a href="http://corp.kaltura.com">video platform</a> <a href="http://corp.kaltura.com/technology/video_management">video management</a> <a href="http://corp.kaltura.com/solutions/overview">video solutions</a> <a href="http://corp.kaltura.com/technology/video_player">video player</a> <a rel="media:thumbnail" href="$x7server/p/$x7kalpartnerid/sp/$x7kalsubpartnerid/thumbnail/entry_id/'+eid+'/width/120/height/90/bgcolor/000000/type/2" /> <span property="dc:description" content="" /><span property="media:title" content="x7Video" /> <span property="media:width" content="400" /><span property="media:height" content="330" /> <span property="media:type" content="application/x-shockwave-flash" /><span property="media:duration" content="{DURATION}" /> </object>';
					
					jQuery('a#x7aplaychange').attr("title",eid);
					jQuery('a#x7aeditchange').attr("title",eid);
					jQuery('a#x7aedit2change').attr("title",eid);
					jQuery('a#x7aeditchange').attr("name",name);
					jQuery('a#x7aedit2change').attr("name",name);
					jQuery('a#x7adelchange').attr("title",eid);
					jQuery('textarea#x7embedchange').val(embedcode);
					jQuery(':input#x7hiddeneidchange').val(eid);
					jQuery('img#x7imgchange').attr("src",thumburl);
					
					Shadowbox.init();
					jQuery('div#x7tablewrap').hide('slow');
					jQuery('div#x7form').show('slow');
					var allowpost = '$x7allowposts';
					if (allowpost=='yes'){
						jQuery('div#x7postform').show('slow');
					}
					postout = 'true';
				} else if(postout == 'true')
				{
					jQuery('div#x7form').hide('slow');
					jQuery('div#x7tablewrap').show('slow');
					postout = 'false';
				}
			}
			function formValidate()
			{
				var title = new LiveValidation('title', {onlyOnSubmit: true });
				title.add( Validate.Presence );
				var keywords = new LiveValidation('keywords', {onlyOnSubmit: true });
				//Pattern matches for comma delimited string
				keywords.add( Validate.Format, { pattern: /([^\"]+?)\",?|([^,]+),?|,/ } );
				var password = new LiveValidation('password', {onlyOnSubmit: true });
				password.add( Validate.Presence );
			}
			//Function that retrieves URL get variables
			function getUrlVars()
			{
				var vars = [], hash;
				var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
				for(var i = 0; i < hashes.length; i++)
				    {
				        hash = hashes[i].split('=');
				        vars.push(hash[0]);
				        vars[hash[0]] = hash[1];
				    }
				return vars;
			}
			var map = getUrlVars();
			//Shows the user success or failure feedback
			function addSuccessDiv() {
			if (map.result=="success"){
				jQuery("#x7loading").prepend("<div class='ui-state-error'>Success! Your post has now been queued for moderation by an administrator.</div><br><br>");
			}
			if (map.result=="fail") {
				jQuery("#x7loading").prepend("<div class='ui-state-error'>Post failed! Please try again.</div><br><br>");
			}
			}
			jQuery(document).ready(function() {
				addSuccessDiv();
				jQuery("td.tt[title]").tooltip();
			
			jQuery("#x7entriestable").dataTable({
				"bJQueryUI": true,
				"bPaginate": true,
				"bProcessing": true,
				"bSort": true,
				"sScrollY": "300px",
				"iDisplayLength": 10,
				"sPaginationType": "full_numbers"
			});
			
			jQuery("#x7entriestable tbody tr").live('click', function() {
				var eid = jQuery(this).attr("title");
				var name = jQuery(this).attr("name");
				x7VidPost(eid, name);
			});
			
			}); //end document ready
DELETE_JS;

		$return .= '</script>';
		//ADD X7LOADING DIV
			$return .= "<div id='x7loading' style='display:none'><p><img border='0' src='$pluginurl/x7video/images/x7loader.gif'></p></div><br /><br />";
		
		//Embed user uploads
		$xmlresult = rest_helper("$x7server/api_v3/?service=media&action=list",
					 array(
						'ks' => $ks,
						'filter:userIdEqual' => $user_login,
						'filter:orderBy' => '-createdAt'
					 ), 'POST'
					 );
						
			//ADD post form
			$return .= <<<X7POSTFORM
			<div class="ui-widget ui-state-highlight ui-corner-all" style="display:none" id="x7form">
				<span style="float:right"><strong>Embed code:</strong><br><textarea id="x7embedchange" cols="25" rows="5"></textarea></span>
				<a onClick="x7VidPlay()" id="x7aplaychange" title=""><strong>Media Entry Details<br><br>
				<img id="x7imgchange" src=""><br><br>[PLAY]</a> |
				<a id="x7aeditchange" name="" title="" onClick="x7VidEditStandard()">[CREATE STANDARD MIX]</a> |
				<a id="x7aedit2change" name="" title="" onClick="x7VidEditAdvanced()">[CREATE ADVANCED MIX]</a> |
				<a id="x7adelchange" title="" onClick="x7VidDelete()">[DELETE]</a>
				<br><br>
				<div id="x7postform" style="display:none">
				<form name="x7postdraft" id="x7postdraft" action="$pluginurl/x7video/x7post.php" method="post">
				<input type="hidden" name="x7server" id="x7server" value="$x7server" >
				<input type="hidden" name="x7kalpartnerid" id="x7kalpartnerid" value="$x7kalpartnerid" >
				<input type="hidden" name="x7uiconfid" id="x7uiconfid" value="$x7uiconfid" >
				<input type="hidden" name="eid" id="x7hiddeneidchange" value="" >
				<input type="hidden" name="rpcurl" id="rpcurl" value="$x7rpcurl" >
				<input type="hidden" name="username" id="username" value="$user_login" >
				<input type="hidden" name="x7fullplugurl" id="x7fullplugurl" value="$x7fullplugurl" >
				<input type="hidden" name="x7bloghome" id="x7bloghome" value="$x7bloghome" >
				<label for="title">Title of Post:</label><br />
				<input type="text" size="25" name="title" id="title" value="" class="" ><br />
				<label for="category">Category(ies):</label><br />
				<select name="category[]" id="category" multiple="multiple" class="">
				$option
				</select><br />
				<label for="description">Description:</label><br />
				<textarea cols="35" rows="4" name="description" id="description" class="" />Another new video from $user_login!</textarea><br />
				<label for="keywords">Tags (comma delimited):</label><br />
				<input type="text" size="25" name="keywords" id="keywords" value="" class="" ><br />
				<label for="password">Wordpress Password:</label><br />
				<input type="password" name="password" id="password" size="20" ><br />
				<input type="submit" value="[Post]" name="submit" id="submit" ></form>
				<a onClick="x7VidPost();">[Cancel]</a>
				</div>
			</div>
X7POSTFORM;

			$return .= "<div id='x7tablewrap'><table id='x7entriestable'><thead><tr><th>Name</th><th>ID</th><th>Description</th><th>Duration</th><th>When Created</th></tr></thead><tbody>";
			
		foreach ($xmlresult->result->objects->item as $mixentry) {
			$eid = $mixentry->id;
			$thumb = $mixentry->thumbnailUrl;
			$userId = $mixentry->userId;
			$name = $mixentry->name;
			$description = $mixentry->description;
			$duration = $mixentry ->duration;
			$createdat = (string) $mixentry->createdAt;
			$createdat = date(DATE_RFC822, $createdat);
                        //only add if the current user is the uploader
			//if ($userId == $user_login) {
				$return .= <<<ENTRY_DIV
				<tr title="$eid" name="$name">
					<td class="tt" title="Click me to open administration menu!">$name</td>
					<td>$eid</td>
					<td>$description</td>
					<td>$duration</td>
					<td>$createdat</td>
				</tr>
ENTRY_DIV;
			//} //end if user login
		} //end foreach
		//End x7entries table
		$return .= "</tbody></table></div>";
	} //end if widget is user upload gallery
	
	if ($widget=="usermixes"){
		//This widget displays the logged in user's Kaltura uploads and offers the ability to
		//play, edit (remix), delete and post them as drafts to the wordpress blog
		//Start Kaltura "Admin" Session
		include_once("KalturaClient.php");
		define("KALTURA_PARTNER_ID", "$x7kalpartnerid");
		define("KALTURA_PARTNER_SERVICE_SECRET", "$x7kaladminsecret");
		$config           = new KalturaConfiguration();
		$config->serviceUrl = $x7server;
		$client           = new KalturaClient($config);
		$type = KalturaSessionType::ADMIN;
		$ks = $client->session->start(KALTURA_PARTNER_SERVICE_SECRET, "$user_login", $type, KALTURA_PARTNER_ID, $expiry, $privileges);
		$ksget = urlencode($ks);
		
		//SET RPCURL XMLRPC FILE VALUE
		$x7rpcurl = $x7bloghome . "/xmlrpc.php";
		$x7fullplugurl = plugins_url('/ixr.php', __FILE__);
		$playurl = plugins_url('x7vidplayer.php', __FILE__);
                        $pluginurl = plugins_url();
                        $pluginurlget = urlencode($pluginurl);
                        $advancedediturl = plugins_url('x7advancededitor.php', __FILE__);
			$standardediturl = plugins_url('x7standardeditor.php', __FILE__);
		//GET CATEGORIES LIST
		$categories = get_categories('hide_empty=0'); 
			foreach ($categories as $cat) {
				$option .= "<option value=\"$cat->cat_name\">$cat->cat_name</option>";
			}
		
		//EMBED DELETE JAVASCRIPT FUNCTION AND POST FUNCTION AND GET VARIABLE READER
		$return.= <<<DELETE_JS
		
		<style type="text/css">
		#x7form { width: 400px; }
		.tooltip {
				display:none;
				background:transparent url($pluginurl/x7video/images/black_arrow.png);
				font-size:12px;
				height:70px;
				width:160px;
				padding:25px;
				color:#fff;	
			}
		</style>
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://cdn.jquerytools.org/1.2.4/jquery.tools.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/shadowbox.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/x7js.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/validator.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/jquery.dataTables.min.js?ver=3.0.1'></script>


		<script type="text/javascript">
		
			function x7VidPlay()
			{
				var eid = jQuery("a#x7aplaychange").attr("title");
				var playurl = '$playurl'+'?eid='+eid+'&x7kalpartnerid=$x7kalpartnerid&x7server=$x7serverget&x7uiconfid=$x7adminuiconfid';
				Shadowbox.open({
					content: playurl,
					player: "iframe",
					height: "370",
					width: "405"
				});
			}
			
			function x7VidEdit()
			{
				var eid = jQuery("a#x7aeditchange").attr("title");
				var name = jQuery("a#x7aeditchange").attr("name");
				var type = jQuery("a#x7aeditchange").attr("type");
				jQuery('div#x7form').hide('slow');
				jQuery('div#x7tablewrap').show('slow');
				if (type == "1"){
					var editurl = '$standardediturl'+'?entryId='+eid+'&ks=$ksget&x7bloghomeget=$x7bloghomeget&x7kalpartnerid=$x7kalpartnerid&x7kalusersecret=$x7kalusersecret&userlogin=$user_login&x7server=$x7serverget&pluginurl=$pluginurlget';
				}
				if (type == "2"){
					var editurl = '$advancedediturl'+'?entryId='+eid+'&ks=$ksget&x7bloghomeget=$x7bloghomeget&x7kalpartnerid=$x7kalpartnerid&x7kalusersecret=$x7kalusersecret&userlogin=$user_login&x7server=$x7serverget&pluginurl=$pluginurlget';
				}
				Shadowbox.open({
					content: editurl,
					player: "iframe",
					height: "600",
					width: "1000"
				});
			}
		
			function x7VidDelete()
			{
				var delid = jQuery("a#x7adelchange").attr("title");
				if (confirm("Warning!  This will affect all playlists that contain mix id: " + delid + ". Continue?"))
				{ 
				    jQuery.post(
				       "$pluginurl/x7video/x7delete.php",
				       {'x7bloghome': '$x7bloghome', 'ks': "$ks", 'x7entrytype': 'mix', 'eid': delid, 'x7server': "$x7server"},
				       function ( response ){
					      jQuery("#x7entriestable tbody tr [title="+delid+"]").remove();
					      jQuery('div#x7form').hide('slow');
						jQuery('div#x7tablewrap').show('slow');
						alert("Mix successfully deleted. Reloading table...");
						window.location.reload();
					      //var x7nodes = x7Table.fnGetNodes();
					      //TODO NEED TO REMOVE APPROPRIATE ROW FROM THE TABLE AND REFRESH TABLE
				       });//end post
				} //end confirm
			} //end x7VidDelete
			var postout;
			postout = 'false';
			function x7VidPost(eid, name, type)
			{
				if (postout == 'false'){
					formValidate();
					var thumburl = '$x7server/p/1/sp/$x7kalpartnerid/thumbnail/entry_id/'+eid+'/width/150/height/120';
					var embedcode = '<object id="kaltura_player" name="kaltura_player" type="application/x-shockwave-flash" allowFullScreen="true" allowNetworking="all" allowScriptAccess="always" height="330" width="400" xmlns:dc="http://purl.org/dc/terms/" xmlns:media="http://search.yahoo.com/searchmonkey/media/" rel="media:video" resource="$x7server/index.php/kwidget/cache_st/1283996450/wid/_100/uiconf_id/$x7uiconfid/entry_id/'+eid+'" data="$x7server/index.php/kwidget/cache_st/1283996450/wid/_100/uiconf_id/$x7uiconfid/entry_id/'+eid+'"><param name="allowFullScreen" value="true" /><param name="allowNetworking" value="all" /><param name="allowScriptAccess" value="always" /><param name="bgcolor" value="#000000" /><param name="flashVars" value="&" /><param name="movie" value="$x7server/index.php/kwidget/cache_st/1283996450/wid/_100/uiconf_id/$x7uiconfid/entry_id/'+eid+'" /><a href="http://corp.kaltura.com">video platform</a> <a href="http://corp.kaltura.com/technology/video_management">video management</a> <a href="http://corp.kaltura.com/solutions/overview">video solutions</a> <a href="http://corp.kaltura.com/technology/video_player">video player</a> <a rel="media:thumbnail" href="$x7server/p/$x7kalpartnerid/sp/$x7kalsubpartnerid/thumbnail/entry_id/'+eid+'/width/120/height/90/bgcolor/000000/type/2" /> <span property="dc:description" content="" /><span property="media:title" content="x7Video" /> <span property="media:width" content="400" /><span property="media:height" content="330" /> <span property="media:type" content="application/x-shockwave-flash" /><span property="media:duration" content="{DURATION}" /> </object>';
					
					jQuery('a#x7aplaychange').attr("title",eid);
					jQuery('a#x7aeditchange').attr("title",eid);
					jQuery('a#x7aeditchange').attr("name",name);
					jQuery('a#x7aeditchange').attr("type",type);
					jQuery('a#x7adelchange').attr("title",eid);
					jQuery('textarea#x7embedchange').val(embedcode);
					jQuery(':input#x7hiddeneidchange').val(eid);
					jQuery('img#x7imgchange').attr("src",thumburl);
					
					Shadowbox.init();
					jQuery('div#x7tablewrap').hide('slow');
					jQuery('div#x7form').show('slow');
					var allowpost = '$x7allowposts';
					if (allowpost=='yes'){
						jQuery('div#x7postform').show('slow');
					}
					postout = 'true';
				} else if(postout == 'true')
				{
					jQuery('div#x7form').hide('slow');
					jQuery('div#x7tablewrap').show('slow');
					postout = 'false';
				}
			}
			function formValidate()
			{
				var title = new LiveValidation('title', {onlyOnSubmit: true });
				title.add( Validate.Presence );
				var keywords = new LiveValidation('keywords', {onlyOnSubmit: true });
				//Pattern matches for comma delimited string
				keywords.add( Validate.Format, { pattern: /([^\"]+?)\",?|([^,]+),?|,/ } );
				var password = new LiveValidation('password', {onlyOnSubmit: true });
				password.add( Validate.Presence );
			}
			//Function that retrieves URL get variables
			function getUrlVars()
			{
				var vars = [], hash;
				var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
				for(var i = 0; i < hashes.length; i++)
				    {
				        hash = hashes[i].split('=');
				        vars.push(hash[0]);
				        vars[hash[0]] = hash[1];
				    }
				return vars;
			}
			var map = getUrlVars();
			//Shows the user success or failure feedback
			function addSuccessDiv() {
			if (map.result=="success"){
				alert("Success! Your post has now been queued for moderation by an administrator.");
			}
			if (map.result=="fail") {
				alert("Post failed! Please try again.");
			}
			}
			jQuery(document).ready(function() {
				addSuccessDiv();
				jQuery("td.tt[title]").tooltip();
				
			x7table = jQuery("#x7entriestable").dataTable({
				"bJQueryUI": true,
				"bPaginate": true,
				"bProcessing": true,
				"bSort": true,
				"sScrollY": "300px",
				"iDisplayLength": 10,
				"sPaginationType": "full_numbers"
			});
			
			jQuery("#x7entriestable tbody tr").live('click', function() {
				var eid = jQuery(this).attr("title");
				var name = jQuery(this).attr("name");
				var type = jQuery(this).attr("type");
				x7VidPost(eid, name, type);
			});
			
			}); //end document ready
DELETE_JS;

		$return .= '</script>';
		//ADD X7LOADING DIV
			$return .= "<div id='x7loading' style='display:none'><p><img border='0' src='$pluginurl/x7video/images/x7loader.gif'></p></div><br /><br />";
		
		//Embed user uploads
		$xmlresult = rest_helper("$x7server/api_v3/?service=mixing&action=list",
					 array(
						'ks' => $ks,
						'filter:userIdEqual' => $user_login,
						'filter:orderBy' => '-createdAt'
					 ), 'POST'
					 );
						
			//ADD post form
			$return .= <<<X7POSTFORM
			<div class="ui-widget ui-state-highlight ui-corner-all" style="display:none" id="x7form">
				<span style="float:right"><strong>Embed code:</strong><br><textarea id="x7embedchange" cols="25" rows="5"></textarea></span>
				<a onClick="x7VidPlay()" id="x7aplaychange" title=""><strong>Mix Details<br><br>
				<img id="x7imgchange" src=""><br><br>[PLAY]</a> |
				<a id="x7aeditchange" name="" title="" onClick="x7VidEdit()">[EDIT MIX]</a> |
				<a id="x7adelchange" title="" onClick="x7VidDelete()">[DELETE]</a>
				<br><br>
				<div id="x7postform" style="display:none">
				<form name="x7postdraft" id="x7postdraft" action="$pluginurl/x7video/x7post.php" method="post">
				<input type="hidden" name="x7server" id="x7server" value="$x7server" >
				<input type="hidden" name="x7uiconfid" id="x7uiconfid" value="$x7uiconfid" >
				<input type="hidden" name="eid" id="x7hiddeneidchange" value="" >
				<input type="hidden" name="rpcurl" id="rpcurl" value="$x7rpcurl" >
				<input type="hidden" name="username" id="username" value="$user_login" >
				<input type="hidden" name="x7fullplugurl" id="x7fullplugurl" value="$x7fullplugurl" >
				<input type="hidden" name="x7bloghome" id="x7bloghome" value="$x7bloghome" >
				<label for="title">Title of Post:</label><br />
				<input type="text" size="25" name="title" id="title" value="" class="" ><br />
				<label for="category">Category(ies):</label><br />
				<select name="category[]" id="category" multiple="multiple" class="">
				$option
				</select><br />
				<label for="description">Description:</label><br />
				<textarea cols="35" rows="4" name="description" id="description" class="" />Another new video from $user_login!</textarea><br />
				<label for="keywords">Tags (comma delimited):</label><br />
				<input type="text" size="25" name="keywords" id="keywords" value="" class="" ><br />
				<label for="password">Wordpress Password:</label><br />
				<input type="password" name="password" id="password" size="20" ><br />
				<input type="submit" value="[Post]" name="submit" id="submit" ></form>
				<a onClick="x7VidPost();">[Cancel]</a>
				</div>
			</div>
X7POSTFORM;

			$return .= "<div id='x7tablewrap'><table id='x7entriestable'><thead><tr><th>Name</th><th>ID</th><th>Description</th><th>Duration (s)</th><th>Editor Type</th><th>When Created</th></tr></thead><tbody>";
			
		foreach ($xmlresult->result->objects->item as $mixentry) {
			$eid = $mixentry->id;
			$thumb = $mixentry->thumbnailUrl;
			$userId = $mixentry->userId;
			$name = $mixentry->name;
			$description = $mixentry->description;
			$duration = $mixentry ->duration;
			$editortype = (string) $mixentry->editorType;
			if ($editortype == "1"){
				$editortypestr = "Simple";
				};
			if ($editortype == "2"){
				$editortypestr = "Advanced";
				};
			$createdat = (string) $mixentry->createdAt;
			$createdat = date(DATE_RFC822, $createdat);
                        //only add if the current user is the uploader
			//if ($userId == $user_login) {
				$return .= <<<ENTRY_DIV
				<tr title="$eid" name="$name" type="$editortype">
					<td class="tt" title="Click me to open administration menu!">$name</td>
					<td>$eid</td>
					<td>$description</td>
					<td>$duration</td>
					<td>$editortypestr</td>
					<td>$createdat</td>
				</tr>
ENTRY_DIV;
			//} //end if user login
		} //end foreach
		//End x7entries table
		$return .= "</tbody></table></div>";
	} //end if widget is user mixes
	
	if ($widget=="userposts"){
		//gotta use wpdb global here to query the database
		global $wpdb;
		//explain that this will only show draft posts
		$return .= <<<WARNING
		
		<style type="text/css">
		.x7drafts { width:800px; }
		</style>
		<div class="ui-widget">
      <div class="ui-state-highlight ui-corner-all" style="padding: 0 .7em;"> 
	    <p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span> 
	    <strong>This page shows your pending posts only (those posts waiting for moderation to be published).  To see your published videos and playlists, check out <a href="$x7bloghome/author/$user_login">your author page</a>.</strong>
      </p></div>
</div>
<br />
WARNING;

		// Extract drafts from database based on parameters
		$drafts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = '$user_ID'");
		// Loop through and output results
		//$return .= var_export($drafts);
		if ($drafts) {
			//setup drafts master div
			$return .= "<div class='x7drafts'>";
			foreach ($drafts as $post) {
				setup_postdata($post);
				$postid = get_the_id();
				$title = get_the_title($postid);
				$content = get_the_content($postid);
				$author = get_the_author($postid);
				$tags = get_the_tags($postid);
				$cats = get_the_category($postid);
				$date = get_the_date();
				$return .= "<div class='ui-widget ui-state-highlight ui-corner-all' style='padding:10px;'><p>";
				$return .= "Post Title: " . $title . "<br>";
				$return .= "Date Submitted: " . $date . "<br>";
				$return .= "Status: Awaiting Moderation<br>";
				$return .= "Content of post:<br><br><br>";
				//$return .= "Tags: " . foreach ($tags as $tag){echo($tag . ', ')} . "<br>";
				//$return .= "Category(ies): " . foreach ($cats as $cat){echo($cat . ', ')} . "<br><br>";
				$return .= $content . "<br><br>";
				$return .="</p></div>";
			} // end foreach
			//close master drafts div
			$return .= "</div>";
			} // end if drafts
		} //end if widget is user posts
		
	if ($widget=="makeplaylist"){
		//Start Kaltura admin session
		include_once("KalturaClient.php");
		define("KALTURA_PARTNER_ID", "$x7kalpartnerid");
		define("KALTURA_PARTNER_SERVICE_SECRET", "$x7kaladminsecret");
		$partnerUserID = 'ANONYMOUS';
		$config           = new KalturaConfiguration();
		$config->serviceUrl = $x7server;
		$client           = new KalturaClient($config);
		$type = KalturaSessionType::ADMIN;
		$ks = $client->session->start(KALTURA_PARTNER_SERVICE_SECRET, "$user_login", $type, KALTURA_PARTNER_ID, $expiry, $privileges);
		
		//add javascript and info box TODO - pull out all CSS and put into external file
		$return .= <<<INFOBOX

		<style type="text/css">
			#vidlist { list-style-type: none; margin: 0px; padding: 0px; border: dashed; border-width: thin; }
			#playlist { width: 153px; height: 110px; list-style-type: none; margin: 0px; padding: 0px; border: dashed; border-width: thin; }
			#playlist li, #vidlist li { padding: 5px; font-size: 1.2em; width: 135px; height: 100px; border: dashed; border-width: thin; }
			#vidlistdiv, #betweendiv, #playlistdiv { float: left; padding:15px; }
			#betweendiv { padding-top: 120px; }
			textarea#listname { width: 160px; height: 20px; border: 3px solid #cccccc; padding: 5px; font-family: Tahoma, sans-serif; }
		</style>
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://cdn.jquerytools.org/1.2.4/jquery.tools.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/shadowbox.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/x7js.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/validator.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/jquery.dataTables.min.js?ver=3.0.1'></script>
		<script type="text/javascript">
		
		//list users created playlists
		jQuery(document).ready(function() {
		//jQuery('#x7loading').html('<p><img border="0" src="$pluginurl/x7video/images/x7loader.gif"></p>');
		jQuery("#vidlist, #playlist").sortable({
			connectWith: '.connectedSortable',
			revert: 'true',
			tolerance: 'pointer',
			placeholder: 'ui-state-highlight'
		}).disableSelection();
		jQuery(".draggable").draggable({
			cursor: 'crosshair',
			cursorAt: { top: 50, left: 50 },
			opacity: '0.6',
			containment: '#x7wrapdiv',
			revert: 'valid',
			revertDuration: '1000',
		});
		jQuery("#listname").val("Playlist Name Here");
	    });//end document ready
		
		function x7ListPreview()
		{
			var valError = "noerror";
			arrEids = []; //clear out the eids array
			var listname;
			jQuery("#playlist li").each(
				function( intindex ){
					arrEids[intindex] = jQuery( this ).attr("eid");
				});
			if (arrEids.length < 2)
			{
				valError = "error";
				alert("New playlists must contain at least two videos!");
			}
			listname = jQuery("#listname").val(); //get entered listname text
			if (listname.length < 5)
			{
				valError = "error";
				alert("Playlist name must contain at least five characters!");
			}
			if (valError != "error")
			{
				jQuery('#x7loading').html('<p><img border="0" src="$pluginurl/x7video/images/x7loader.gif"></p>');
				jQuery.post(
					"$pluginurl/x7video/x7listadd.php",
					{'x7server': "$x7server", 'x7kalpartnerid': "$x7kalpartnerid", 'ks': "$ks", 'eids[]': arrEids, 'listname': listname, 'ul': "$user_login", 'x7bloghome': "$x7bloghome"},
					function ( data ){
						jQuery("#x7loading").html('');
						if (data != "error"){
							var theUrl;
							theUrl = "$pluginurl/x7video/x7listplayer.php";
							Shadowbox.open({
							content:    theUrl + "?listid=" + data + "&x7kalpartnerid=$x7kalpartnerid&x7serverget=$x7serverget&x7pluiconfid=$x7pluiconfid",
							player:     "iframe",
							height:     400,
							width:      800
							});
						} else {
							alert("Error creating playlist.");
						}; //end if not server data returned error
					}); //end post
	    };//end if not valerror error
		}//end x7listpreview
		
		</script>
		<div class="ui-widget">
      <div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;"> 
	    <p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
	    <strong>Quick tip:  </strong>This page lets you make playlists only from videos and mixes that you yourself have uploaded and made.</p>
      </div>
		</div>
		<br>
		<br>
		<div id="wrapdiv" style="width:500px;margin-left:auto;margin-right:auto;">
		<div id="vidlistdiv" style="height:1000px">
			<h3>Your Movies</h3>
			<ul id="vidlist" class="connectedSortable">
INFOBOX;
		$mediaresult = rest_helper("$x7server/api_v3/?service=media&action=list",
					 array(
						'ks' => $ks,
						'filter:userIdEqual' => $user_login,
						'filter:orderBy' => '-createdAt'
					 ), 'POST'
					 );
		foreach ($mediaresult->result->objects->item as $mediaentry) {
			$eid = $mediaentry->id;
			$thumb = $mediaentry->thumbnailUrl;
			$userId = $mediaentry->userId;
			$name = $mediaentry->name;
			$description = $mediaentry->description;
			$duration = $mediaentry ->duration;
			$return .= <<<ENTRY_DIV
				<li class="ui-state-default" eid="$eid">
				<img style="padding-top:10px" eid="$eid" title="Media - $name, $duration seconds" src="$thumb">
				</li>
ENTRY_DIV;
		} //end foreach
		$mixresult = rest_helper("$x7server/api_v3/?service=mixing&action=list",
					 array(
						'ks' => $ks,
						'filter:userIdEqual' => $user_login,
						'filter:orderBy' => '-createdAt'
					 ), 'POST'
					 );
		foreach ($mixresult->result->objects->item as $mixentry) {
			$eid = $mixentry->id;
			$thumb = $mixentry->thumbnailUrl;
			$userId = $mixentry->userId;
			$name = $mixentry->name;
			$description = $mixentry->description;
			$duration = $mixentry ->duration;
			$return .= <<<ENTRY_DIV2
				<li class="ui-state-default" eid="$eid">
				<img style="padding-top:10px" eid="$eid" title="Mix - $name, $duration seconds" src="$thumb">
				</li>
ENTRY_DIV2;
		} //end foreach
		$return .= <<<INFOBOX2
		
			</ul>
		</div>
		<div id="betweendiv">
			<div id="x7loading"></div>
			DRAG==><br>AND<br>
			<==DROP!
		</div>
		<div id="playlistdiv">
			<h3>New Playlist</h3>
			<a onclick="x7ListPreview()">[Save and Preview]</a><br />
			<textarea id="listname"></textarea>
			<ul id="playlist" class="connectedSortable">
			</ul>
		</div>
		</div>
INFOBOX2;
		
	} // end if widget is makeplaylist
	
	if ($widget=="userplaylists"){
	
		//Start Kaltura admin session
		include_once("KalturaClient.php");
		define("KALTURA_PARTNER_ID", "$x7kalpartnerid");
		define("KALTURA_PARTNER_SERVICE_SECRET", "$x7kaladminsecret");
		$partnerUserID = 'ANONYMOUS';
		$config           = new KalturaConfiguration();
		$config->serviceUrl = $x7server;
		$client           = new KalturaClient($config);
		$type = KalturaSessionType::ADMIN;
		$ks = $client->session->start(KALTURA_PARTNER_SERVICE_SECRET, "$user_login", $type, KALTURA_PARTNER_ID, $expiry, $privileges);
		$ksget = urlencode($ks);
		
		//SET RPCURL XMLRPC FILE VALUE
		$x7rpcurl = $x7bloghome . "/xmlrpc.php";
		$x7fullplugurl = plugins_url('/ixr.php', __FILE__);
		$playurl = plugins_url('x7vidplayer.php', __FILE__);
                        $pluginurl = plugins_url();
                        $pluginurlget = urlencode($pluginurl);
                        $editurl = plugins_url('x7advancededitor.php', __FILE__);
		//GET CATEGORIES LIST
		$categories = get_categories('hide_empty=0'); 
			foreach ($categories as $cat) {
				$option .= "<option value=\"$cat->cat_name\">$cat->cat_name</option>";
			}
		
		//add javascript and styles
		$return .= <<<USERPLJS
		
		<style type="text/css">
		
			#x7wrapdiv, #x7loading { display: none; }
			#sortable, #trash { list-style-type: none; margin: 0; padding: 0; width: 100px; }
			#sortable li, #trash li { margin: 0 5px 5px 5px; padding: 5px; width: 90px; height: 60px; }
			html>body #sortable li { height: 61px; line-height: 1.2em; }
			html>body #trash li { height: 91px; line-height: 1.2em; }
			.ui-state-highlight { height: 1.5em; line-height: 1.2em; }
			textarea#listname { width: 160px; height: 20px; border: 3px solid #cccccc; padding: 5px; font-family: Tahoma, sans-serif; }	    
			/* root element for scrollable */
.vertical {  
	
	/* required settings */
	position:relative;
	overflow:hidden;	

	/* vertical scrollers have typically larger height than width */	
	height: 270px;	 
	width: 550px;
	border-top:1px solid #ddd;	
}

/* root element for scrollable items */
.items {	
	position:absolute;
	
	/* this time we have very large space for height */	
	height:20000em;	
	margin: 0px;
}

/* single scrollable item */
.item {
	border-bottom:1px solid #ddd;
	margin:10px 0;
	padding:15px;
	font-size:12px;
	height:100px;
}

/* elements inside single item */
.item img {
	float:left;
	margin-right:20px;
	height:90px;
	width:110px;
}

.item h3 {
	margin:0 0 5px 0;
	font-size:16px;
	color:#456;
	font-weight:normal;
}

/* the action buttons above the scrollable */
#actions {
	width:500px;
	margin:30px 0 10px 0;	
}

#actions a {
	font-size:11px;		
	cursor:pointer;
	color:#666;
}

#actions a:hover {
	text-decoration:underline;
	color:#000;
}

.disabled {
	visibility:hidden;		
}

.next {
	float:right;
}	
		</style>
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://cdn.jquerytools.org/1.2.4/jquery.tools.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/shadowbox.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/x7js.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/validator.js?ver=3.0.1'></script>
		<script type='text/javascript' src='$pluginurl/x7video/js/jquery.dataTables.min.js?ver=3.0.1'></script>
		<script type="text/javascript">
		//Function that retrieves URL get variables
			function getUrlVars()
			{
				var vars = [], hash;
				var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
				for(var i = 0; i < hashes.length; i++)
				    {
				        hash = hashes[i].split('=');
				        vars.push(hash[0]);
				        vars[hash[0]] = hash[1];
				    }
				return vars;
			}
			var map = getUrlVars();
			//Shows the user success or failure feedback
			function addSuccessDiv() {
			if (map.result=="success"){
				alert("Success! Your post has now been queued for moderation by an administrator.");
			}
			if (map.result=="fail") {
				alert("Post failed! Please try again.");
			}
			} //end addsuccessdiv
			
			function formValidate()
			{
				var title = new LiveValidation('title', {onlyOnSubmit: true });
				title.add( Validate.Presence );
				var keywords = new LiveValidation('keywords', {onlyOnSubmit: true });
				//Pattern matches for comma delimited string
				keywords.add( Validate.Format, { pattern: /([^\"]+?)\",?|([^,]+),?|,/ } );
				var password = new LiveValidation('password', {onlyOnSubmit: true });
				password.add( Validate.Presence );
			} //end validate
			
		jQuery(document).ready(function() {
			addSuccessDiv();
			//jQuery('#x7loading').html('<p><img border="0" src="$pluginurl/x7video/images/x7loader.gif"></p>');
			
			//make playlist entries sortable
			jQuery("#sortable").sortable({
				placeholder: 'ui-state-highlight'
			});
			jQuery("#sortable").disableSelection();
			
			//make playlists scrollable
			jQuery(".scrollable").scrollable({
				    vertical:true
			      });
			
			jQuery(".item").mouseover(function(){
				jQuery(this).addClass("ui-state-default");  
			}).mouseout(function(){
				jQuery(this).removeClass("ui-state-default");  
			});
			
			jQuery("#droppable").droppable({
				activeClass: 'ui-state-hover',
				hoverClass: 'ui-state-active',
				drop: function(event, ui) {
					var eid = ui.draggable.attr("eid");
					jQuery("#sortable li[eid="+ eid +"]").hide('slow');
					jQuery("#sortable li[eid="+ eid +"]").remove();
				}
			});
			}); //end document ready
		function x7ListPost(eid)
		{
				formValidate();
				jQuery(':input#x7hiddeneidchange').val(eid);
				jQuery('#x7listwrap').hide('slow');
				jQuery("#x7form").show('slow');
				postout='true';
		}
		
		function x7FormClose()
		{
			jQuery("#x7form").hide('slow');
			jQuery('#x7listwrap').show('slow');
		}
	  
		function x7VidDelete(delid)
			{
				if (confirm("Are you sure you want to delete playlist ID: " + delid))
				{ 
				    jQuery.post(
				       "$pluginurl/x7video/x7delete.php",
				       {'x7bloghome': '$x7bloghome', 'ks': "$ks", 'x7entrytype': 'playlist', 'eid': delid, 'x7server': "$x7server"},
				       function ( response ){
					      jQuery("div#"+delid).remove();
						alert("Playlist ID: "+delid+" successfully deleted.");
				       });//end post
				} //end confirm
			} //end x7VidDelete
			
			function x7VidPlay(theEntry)
			{
				x7EditClose();
				var theUrl;
				theUrl = "$pluginurl/x7video/x7listplayer.php";
			    Shadowbox.open({
			    content:    theUrl + "?listid=" + theEntry + "&x7kalpartnerid=$x7kalpartnerid&x7serverget=$x7serverget&x7pluiconfid=$x7pluiconfid",
			    player:     "iframe",
			    height:     330,
			    width:      740
			    });
			}
			
			function x7VidEdit(eid, name)
			{
				var theUrl = "$pluginurl/x7video/x7pledit.php";
				Shadowbox.open({
					content: theUrl + "?ks=$ksget&x7bloghomeget=$x7bloghomeget&x7server=$x7serverget&x7kalpartnerid=$x7kalpartnerid&pluginurl=$pluginurlget&eid="+eid+"&listname="+name,
					player: "iframe",
					height: 700,
					width: 400
				});
			}//end x7videdit
		
		function x7EditClose()
		{
			jQuery("#x7wrapdiv").hide('slow');
			jQuery('#x7listwrap').show('slow');
		}
			</script>
			
			<div class="ui-widget ui-state-highlight ui-corner-all ui-helper-clearfix" style="display:none;width:260px;height:380px;" id="x7form">
				<div id="x7postform">
				<form name="x7postlist" id="x7postlist" action="$pluginurl/x7video/x7plpost.php" method="post">
				<input type="hidden" name="x7server" id="x7server" value="$x7server" >
				<input type="hidden" name="x7kalpartnerid" id="x7kalpartnerid" value="$x7kalpartnerid" >
				<input type="hidden" name="x7pluiconfid" id="x7pluiconfid" value="$x7pluiconfid" >
				<input type="hidden" name="eid" id="x7hiddeneidchange" value="" >
				<input type="hidden" name="rpcurl" id="rpcurl" value="$x7rpcurl" >
				<input type="hidden" name="username" id="username" value="$user_login" >
				<input type="hidden" name="x7fullplugurl" id="x7fullplugurl" value="$x7fullplugurl" >
				<input type="hidden" name="x7bloghome" id="x7bloghome" value="$x7bloghome" >
				<label for="title">Title of Post:</label><br />
				<input type="text" size="25" name="title" id="title" value="" class="" ><br />
				<label for="category">Category(ies):</label><br />
				<select name="category[]" id="category" multiple="multiple" class="">
				$option
				</select><br />
				<label for="description">Description:</label><br />
				<textarea cols="35" rows="4" name="description" id="description" class="" />Another new playlist from $user_login!</textarea><br />
				<label for="keywords">Tags (comma delimited):</label><br />
				<input type="text" size="25" name="keywords" id="keywords" value="" class="" ><br />
				<label for="password">Wordpress Password:</label><br />
				<input type="password" name="password" id="password" size="20" ><br />
				<input type="submit" value="[Post]" name="submit" id="submit" ></form>
				<a onClick="x7FormClose();">[Cancel]</a>
				</div>
			</div>
			
			<div id="x7loading"></div><br><br>
			
<div id="x7listwrap">
<div id="actions">
	<a class="prev">&laquo; Previous</a>
	<a class="next">More playlists &raquo;</a>
</div>
<div class="scrollable vertical">
<div class="items">
USERPLJS;
$plresult = rest_helper("$x7server/api_v3/?service=playlist&action=list",
					 array(
						'ks' => $ks,
						'filter:userIdEqual' => $user_login,
						'filter:orderBy' => '-createdAt'
					 ), 'POST'
					 );
		foreach ($plresult->result->objects->item as $plentry) {
			$eid = $plentry->id;
			$thumb = $plentry->thumbnailUrl;
			$userId = $plentry->userId;
			$name = $plentry->name;
			$description = $plentry->description;
			$duration = $plentry ->duration;
			$return .= <<<ENTRY_DIV3
				<div class="item ui-widget-content ui-corner-all" id="$eid">
				<strong>Name</strong>: $name<br>
				<img alt="$eid" style="margin-left:20px" class="tt" src="http://www.kalturacehost.com/wp-content/uploads/video.png" height="90" width="90">
				<a onClick="x7VidPlay('$eid')">[PLAY]</a> |
				<a onClick="x7VidEdit('$eid', '$name')">[EDIT]</a> |
				<a onClick="x7VidDelete('$eid')">[DELETE]</a> |
				<a onClick="x7ListPost('$eid')">[POST]</a>
				<span style="margin-left:20px;float:right;">
				<strong>Embed code:</strong><br>
				<textarea cols="20" rows="2"><object id="kaltura_player" name="kaltura_player" type="application/x-shockwave-flash" allowFullScreen="true" allowNetworking="all" allowScriptAccess="always" height="620" width="400" xmlns:dc="http://purl.org/dc/terms/" xmlns:media="http://search.yahoo.com/searchmonkey/media/" rel="media:video" resource="$x7server/index.php/kwidget/cache_st/1284005068/wid/_$x7kalpartnerid/uiconf_id/$x7pluiconfid" data="$x7server/index.php/kwidget/cache_st/1284005068/wid/_$x7kalpartnerid/uiconf_id/$x7pluiconfid"><param name="allowFullScreen" value="true" /><param name="allowNetworking" value="all" /><param name="allowScriptAccess" value="always" /><param name="bgcolor" value="#000000" /><param name="flashVars" value="playlistAPI.autoContinue=true&playlistAPI.autoInsert=true&playlistAPI.kpl0Name=test&playlistAPI.kpl0Url=$x7serverget%2Findex.php%2Fpartnerservices2%2Fexecuteplaylist%3Fuid%3D%26partner_id%3D$x7kalpartnerid%26subp_id%3D$x7kalsubpartnerid%26format%3D8%26ks%3D%7Bks%7D%26playlist_id%3D$eid&" /><param name="movie" value="$x7server/index.php/kwidget/cache_st/1284005068/wid/_$x7kalpartnerid/uiconf_id/$x7pluiconfid" /><a href="http://corp.kaltura.com">video platform</a> <a href="http://corp.kaltura.com/technology/video_management">video management</a> <a href="http://corp.kaltura.com/solutions/overview">video solutions</a> <a href="http://corp.kaltura.com/technology/video_player">video player</a> {SEO} </object></textarea>
				</span>
				</div>
ENTRY_DIV3;

		} //end foreach
		$return .= "</div></div></div>";
	
	}//end if widget is user playlists
	
	} else {
	$return = "You must be logged in for access.";
}
	return "$return";
} //end shortcode function
add_shortcode('x7video', 'x7video_func');

//SETTINGS PAGE!!!
function x7_settings_page() {
?>
<div class="wrap">
<h2>x7Host UGC Video Plugin Settings</h2>

<form method="post" action="options.php">
    <?php settings_fields( 'x7-settings-group' ); ?>
    <table class="form-table">
	<strong>You MUST enter values for all options fields for the plugin to function properly.</strong>
        <tr valign="top">
        <th scope="row">KalturaCE Server URL</th>
        <td><input type="text" name="x7server" value="<?php echo get_option('x7server'); ?>" /></td>
		<td><em>Example: http://myKalturaServer.MyDomain.com (without trailing slash!)</em></td>
        </tr>
	
	    <tr valign="top">
        <th scope="row">KalturaCE Partner ID</th>
        <td><input type="text" name="x7kalpartnerid" value="<?php echo get_option('x7kalpartnerid'); ?>" /></td>
		<td><em>Example: 100</em></td>
        </tr>
		
		        <tr valign="top">
        <th scope="row">KalturaCE Shared User Secret</th>
        <td><input type="text" name="x7kalusersecret" value="<?php echo get_option('x7kalusersecret'); ?>" /></td>
		<td><em>Example: 8ac76d15a5730302b45230a2fe4f2243 (don't confuse with admin secret!)</em></td>
        </tr>
			
	<th scope="row">KalturaCE Shared Admin Secret</th>
        <td><input type="text" name="x7kaladminsecret" value="<?php echo get_option('x7kaladminsecret'); ?>" /></td>
		<td><em>Example: 66e58e10b8e9f2816eb5bb602839c9ee (don't confuse with user secret!)</em></td>
        </tr>
	
	<tr valign="top">
        <th scope="row">KalturaCE Default Video Player UIConfID (Single Video)</th>
        <td><input type="text" name="x7uiconfid" value="<?php echo get_option('x7uiconfid'); ?>" /></td>
        <td><em>Example: 172876 (find your UIConfID in the Application Studio of <a href="<?php echo get_option('x7server'); ?>/kmc" target="_new">your KMC</a>)</em></td>
		</tr>
	
	<tr valign="top">
        <th scope="row">KalturaCE Default Video Player UIConfID (Playlist)</th>
        <td><input type="text" name="x7pluiconfid" value="<?php echo get_option('x7pluiconfid'); ?>" /></td>
        <td><em>Example: 172877 (find your UIConfID in the Application Studio of <a href="<?php echo get_option('x7server'); ?>/kmc" target="_new">your KMC</a>)</em></td>
		</tr>
	
	<tr valign="top">
        <th scope="row">KalturaCE Default Video Player Admin UIConfID (Logged In Users)</th>
        <td><input type="text" name="x7adminuiconfid" value="<?php echo get_option('x7adminuiconfid'); ?>" /></td>
        <td><em>Example: 172878 (this is the player that you configure with extra abilities, such as downloading and capturing thumbnails, displayed only to your logged in users - it can be the same as your regular single video player)</em></td>
		</tr>
		
	<tr valign="top">
        <th scope="row">KalturaCE Default KCW UIConfID</th>
        <td><input type="text" name="x7kcwuiconfid" value="<?php echo get_option('x7kcwuiconfid'); ?>" /></td>
        <td><em>Example: 1727883 (Default KalturaCE KCW UIConfID is 1727883, but you can use a custom UIConf here)</em></td>
		</tr>
	
	<tr valign="top">
        <th scope="row">KalturaCE KCW Default KShow ID</th>
        <td><input type="text" name="x7kshowid" value="<?php echo get_option('x7kshowid'); ?>" /></td>
		<td><em>Recommended to leave this as a roughcut "-2" unless you really know what you are doing!</em></td>
        </tr>
	
	<tr valign="top">
        <th scope="row">KalturaCE Default Terms Of Use URL</th>
        <td><input type="text" name="x7tou" value="<?php echo get_option('x7tou'); ?>" /></td>
        <td><em>Example: http://www.mydomain.com/termsofuse.html</em></td>
		</tr>
	
	<tr valign="top">
        <th scope="row">Allow User Posts?</th>
        <td><input type="text" name="x7allowposts" value="<?php echo get_option('x7allowposts'); ?>" /></td>
        <td><em>Example: MUST be either "yes" or "no" to allow or disallow user posting of entries, mixes and playlists.</em></td>
		</tr>
    </table>
    
    <p class="submit">
    <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
    </p>

</form>
</div>
<?php } ?>